package com.fang.transfer.file.listener;

import com.fang.transfer.file.common.RequestListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 监听器管理
 */
@Service
public class RequestListenerManagement {

    private Map<String, RequestListener> requestListenerMap = new HashMap<>();

    public RequestListenerManagement(@Autowired List<RequestListener> requestListeners) {
        for (RequestListener listener : requestListeners) {
            String code = listener.getCode();
            checkCode(code);
            requestListenerMap.put(code, listener);
        }
    }


    private void checkCode(String code) {
        RequestListener listener = requestListenerMap.get(code);
        if (listener != null) {
            throw new RuntimeException("RequestListener  code  repeat:" + code + " class:" + listener.getClass().getName());
        }
    }

    public RequestListener getByCode(String code) {
        RequestListener listener = requestListenerMap.get(code);
        if (listener == null) {
            throw new RuntimeException("RequestListener  code:" + code + "");
        }
        return listener;
    }


}
